package group.rober.auth.interceptor;

import group.rober.auth.AuthConsts;
import group.rober.auth.entity.User;
import group.rober.auth.holder.AuthHolder;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthHolderInterceptor implements HandlerInterceptor {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getSession().getAttribute(AuthConsts.SESSION_USER);
        if(user != null){
            AuthHolder.setUser(user);
        }

        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = AuthHolder.getUser();
        if(user==null){
            user = new User();
            user.setCode("anon");
            user.setName("匿名用户");
        }
        if(modelAndView!=null){
            modelAndView.getModelMap().put("sessionUser",user);
        }
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
